// 简单实现 Redux
function createStore(reducer, enhancer) {
    // 处理中间件
    if (enhancer) {
        return enhancer(createStore)(reducer);
    }
    
    let currentState = undefined;
    let listeners = [];

    function getState() {
        return currentState;
    }

    function subscribe(listener) {
        listeners.push(listener);
        return () => {
            listeners = listeners.filter(l => l !== listener);
        };
    }

    function dispatch(action) {
        currentState = reducer(currentState, action);
        listeners.forEach(listener => listener());
        return action;
    }

    // 初始化 state
    dispatch({ type: '@@redux/INIT' });

    return {
        getState,
        subscribe,
        dispatch
    };
}

// 简单实现 React-Redux 的核心功能
function connect(mapStateToProps, mapDispatchToProps) {
    return function(WrappedComponent) {
        return class Connect extends React.Component {
            static contextType = ReactReduxContext;

            constructor(props) {
                super(props);
                this.state = {
                    stateProps: mapStateToProps(this.context.store.getState(), props)
                };
            }

            componentDidMount() {
                this.unsubscribe = this.context.store.subscribe(() => {
                    this.setState({
                        stateProps: mapStateToProps(this.context.store.getState(), this.props)
                    });
                });
            }

            componentWillUnmount() {
                this.unsubscribe();
            }

            render() {
                const dispatchProps = mapDispatchToProps 
                    ? mapDispatchToProps(this.context.store.dispatch, this.props)
                    : { dispatch: this.context.store.dispatch };

                return <WrappedComponent 
                    {...this.props}
                    {...this.state.stateProps}
                    {...dispatchProps}
                />;
            }
        };
    };
}

// Provider 组件
const Provider = ({ store, children }) => {
    return (
        <ReactReduxContext.Provider value={{ store }}>
            {children}
        </ReactReduxContext.Provider>
    );
};
  
// 中间件实现示例：redux-thunk
const thunk = ({ dispatch, getState }) => next => action => {
    if (typeof action === 'function') {
        return action(dispatch, getState);
    }
    return next(action);
};

// 中间件链式调用
function applyMiddleware(...middlewares) {
    return (createStore) => (reducer) => {
        const store = createStore(reducer);
        let dispatch = store.dispatch;

        const middlewareAPI = {
            getState: store.getState,
            dispatch: (action) => dispatch(action)
        };

        const chain = middlewares.map(middleware => middleware(middlewareAPI));
        dispatch = compose(...chain)(store.dispatch);

        return {
            ...store,
            dispatch
        };
    };
}

// 辅助函数
function compose(...funcs) {
    if (funcs.length === 0) return arg => arg;
    if (funcs.length === 1) return funcs[0];
    return funcs.reduce((a, b) => (...args) => a(b(...args)));
}
// 使用示例
// 1. 定义reducer
const initialState = { count: 0 };
const counterReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return { count: state.count + 1 };
        case 'DECREMENT':
            return { count: state.count - 1 };
        default:
            return state;
    }
};

// 2. 创建store
const store = createStore(
    counterReducer,
    applyMiddleware(thunk)
);

// 3. 异步action creator
const incrementAsync = () => dispatch => {
    setTimeout(() => {
        dispatch({ type: 'INCREMENT' });
    }, 1000);
};

// 4. 组件连接示例
const mapStateToProps = state => ({
    count: state.count
});

const mapDispatchToProps = dispatch => ({
    onIncrement: () => dispatch({ type: 'INCREMENT' }),
    onDecrementAsync: () => dispatch(incrementAsync())
});

const ConnectedCounter = connect(
    mapStateToProps,
    mapDispatchToProps
)(Counter);